<template>
  <div id="userInfoPage" class="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 py-8 px-4 transition-all duration-300">
    <!-- 背景装饰 -->
    <div class="fixed inset-0 -z-10 overflow-hidden">
      <div class="absolute -top-20 -right-20 w-60 h-60 bg-blue-100 rounded-full mix-blend-multiply filter blur-3xl opacity-40 animate-pulse"></div>
      <div class="absolute top-1/3 -left-20 w-60 h-60 bg-indigo-100 rounded-full mix-blend-multiply filter blur-3xl opacity-30 animate-pulse" style="animation-delay: 1s;"></div>
    </div>

    <!-- 页面标题和返回按钮 -->
    <div class="max-w-750px mx-auto mb-6 flex justify-between items-center">
      <div>
        <h1 class="text-2xl font-bold text-slate-800 tracking-tight">个人信息设置</h1>
        <p class="text-slate-500 mt-1">管理您的个人资料和账户信息</p>
      </div>
      <a-button
        @click="host"
        class="text-slate-600 hover:text-slate-900 bg-white hover:bg-slate-50 border border-slate-200 transition-all duration-200"
      >
        <ArrowLeftOutlined /> 返回
      </a-button>
    </div>

    <!-- 主卡片 -->
    <a-card
      title="个人资料"
      style="max-width: 750px; margin: 0 auto;"
      class="overflow-hidden transition-all duration-300 hover:shadow-md transform hover:-translate-y-1"
    >
      <a-row :gutter="32" class="py-4">
        <!-- 头像区域 -->
        <a-col :span="8" class="avatar-col">
          <div class="avatar-wrapper">
            <!-- 头像预览 -->
            <div class="avatar-container group cursor-pointer">
              <!-- 头像图片 -->
              <img
                v-if="form.userAvatar"
                :src="form.userAvatar"
                alt="用户头像"
                class="avatar-img transition-all duration-500 group-hover:scale-105"
              />
              <div v-else class="avatar-placeholder transition-all duration-300 group-hover:bg-slate-100">
                <UserOutlined class="avatar-icon" />
                <div class="avatar-text">上传头像</div>
              </div>

              <!-- 悬停操作按钮 -->
              <div class="avatar-overlay opacity-0 group-hover:opacity-100 transition-all duration-300 flex items-center justify-center">
                <a-button
                  type="primary"
                  size="small"
                  class="avatar-btn shadow-md"
                  @click.stop="handleAvatarUpload"
                >
                  <UploadOutlined /> 更换
                </a-button>
              </div>
            </div>

            <p class="avatar-hint mt-2 text-sm text-slate-500">支持JPG、PNG格式，建议尺寸200x200px</p>
          </div>
        </a-col>

        <!-- 表单区域 -->
        <a-col :span="16">
          <a-form
            :model="form"
            layout="vertical"
            ref="formRef"
            @finish="onFinish"
            class="space-y-5"
          >
            <!-- 用户名 -->
            <a-form-item
              label="用户名"
              name="userName"
              :rules="[{ required: true, message: '请输入用户名' }]"
              class="transition-all duration-200"
            >
              <a-input
                v-model:value="form.userName"
                placeholder="请输入用户名"
                class="transition-all duration-200 focus:border-blue-500"
              />
            </a-form-item>

            <!-- 用户账号（不可编辑） -->
            <a-form-item
              label="用户账号"
              name="userAccount"
              class="transition-all duration-200"
            >
              <a-input
                v-model:value="form.userAccount"
                disabled
                class="bg-slate-50"
              />
            </a-form-item>

            <!-- 个人简介 -->
            <a-form-item
              label="个人简介"
              name="userProfile"
              class="transition-all duration-200"
            >
              <a-textarea
                v-model:value="form.userProfile"
                placeholder="请输入个人简介"
                :rows="4"
                class="transition-all duration-200 focus:border-blue-500"
              />
            </a-form-item>

            <!-- 提交按钮 -->
            <a-form-item class="pt-2">
              <a-button
                type="primary"
                html-type="submit"
                @click="handleSubmit"
                block
                class="py-6 text-base font-medium bg-gradient-to-r from-blue-500 to-indigo-500 hover:from-blue-600 hover:to-indigo-600 transition-all duration-300 shadow-sm hover:shadow-lg relative overflow-hidden group"
              >
                <span class="relative z-10">保存修改</span>
                <span class="absolute inset-0 bg-white opacity-0 group-hover:opacity-10 transition-opacity duration-300"></span>
              </a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-card>

    <!-- 头像上传输入（隐藏） -->
    <input
      type="file"
      ref="fileInputRef"
      hidden
      accept="image/*"
      @change="handleFileSelect"
    />

    <!-- 头像裁剪模态框 -->
    <a-modal
      :visible="cropVisible"
      title="裁剪头像"
      :maskClosable="false"
      :width="500"
      @cancel="closeCropModal"
      class="avatar-crop-modal"
      :maskStyle="{ backgroundColor: 'rgba(0, 0, 0, 0.5)' }"
    >
      <div class="crop-container">
        <!-- 裁剪区域 -->
        <div class="crop-box">
          <img
            ref="cropImage"
            :src="cropImageSrc"
            alt="裁剪预览"
            class="crop-img"
          />
        </div>

        <!-- 预览区域 -->
        <div class="preview-container mt-4">
          <p class="preview-title text-sm font-medium text-slate-700">预览：</p>
          <div class="preview-boxes flex gap-4 mt-2">
            <div class="preview-box">
              <div class="preview-label text-xs text-slate-500">大</div>
              <div class="preview-item large" :style="{ backgroundImage: `url(${previewImage})` }"></div>
            </div>
            <div class="preview-box">
              <div class="preview-label text-xs text-slate-500">中</div>
              <div class="preview-item medium" :style="{ backgroundImage: `url(${previewImage})` }"></div>
            </div>
            <div class="preview-box">
              <div class="preview-label text-xs text-slate-500">小</div>
              <div class="preview-item small" :style="{ backgroundImage: `url(${previewImage})` }"></div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <a-button @click="closeCropModal">取消</a-button>
        <a-button
          type="primary"
          @click="confirmCrop"
          class="bg-blue-500 hover:bg-blue-600"
        >
          确认裁剪
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { getUserInfoVoUsingGet, updateUserInfoUsingPost } from '@/api/userController'
import { uploadUserAvatarUsingPost } from '@/api/testController'
import { message, Modal } from 'ant-design-vue'
import { ArrowLeftOutlined, UploadOutlined, UserOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { useRouter } from 'vue-router'
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'

const userLoginStore = useLoginUserStore()
const router = useRouter()

// 表单数据结构
interface UserInfoForm {
  id?: number
  userName?: string
  userAccount?: string
  userAvatar?: string
  userProfile?: string
}

// 响应式变量
const form = ref<UserInfoForm>({})
const fileInputRef = ref<HTMLInputElement | null>(null)
const formRef = ref()
const cropVisible = ref(false)
const cropImage = ref<HTMLImageElement | null>(null)
const cropImageSrc = ref('')
const previewImage = ref('')
const cropper = ref<Cropper | null>(null)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfoVoUsingGet()
    if (res.data.code === 0) {
      form.value = {
        id: res.data.data?.id,
        userName: res.data.data?.userName,
        userAccount: res.data.data?.userAccount,
        userAvatar: res.data.data?.userAvatar,
        userProfile: res.data.data?.userProfile,
      }
    } else {
      message.error('获取用户信息失败: ' + res.data.message)
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    message.error('网络异常，请稍后再试')
  }
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isValidSize = file.size / 1024 / 1024 < 2 // 小于 2MB

  if (!isValidType) {
    message.error('只能上传 JPG/PNG/GIF 格式图片!')
    return false
  }

  if (!isValidSize) {
    message.error('图片大小不能超过 2MB!')
    return false
  }

  return true
}

// 打开文件选择
const handleAvatarUpload = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click()
  }
}

// 处理文件选择
const handleFileSelect = (e: Event) => {
  const input = e.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]

    if (!beforeUpload(file)) {
      input.value = ''
      return
    }

    // 读取文件并显示裁剪框
    const reader = new FileReader()
    reader.onload = (e) => {
      cropImageSrc.value = e.target?.result as string
      cropVisible.value = true

      // 初始化裁剪器
      nextTick(() => {
        if (cropImage.value) {
          if (cropper.value) {
            cropper.value.destroy()
          }

          cropper.value = new Cropper(cropImage.value, {
            aspectRatio: 1, // 1:1比例
            viewMode: 1,
            dragMode: 'move',
            autoCropArea: 0.8, // 默认裁剪区域大小
            restore: false,
            guides: true, // 显示裁剪框的虚线
            center: true, // 显示中心十字线
            highlight: true, // 高亮显示裁剪区域
            cropBoxMovable: true, // 裁剪框可移动
            cropBoxResizable: true, // 裁剪框可调整大小
            toggleDragModeOnDblclick: false,
            ready: () => {
              // 裁剪框准备就绪后更新预览
              updatePreview()
            },
            crop: () => {
              // 裁剪区域变化时更新预览
              updatePreview()
            }
          })
        }
      })
    }
    reader.readAsDataURL(file)
    input.value = '' // 重置以允许重复选择同一文件
  }
}

// 更新预览
const updatePreview = () => {
  if (cropper.value) {
    previewImage.value = cropper.value.getCroppedCanvas().toDataURL()
  }
}

// 确认裁剪
const confirmCrop = async () => {
  if (cropper.value) {
    try {
      // 显示加载状态
      Modal.success({
        content: '正在上传头像...',
        maskClosable: false,
        closable: false,
        icon: null
      })

      // 获取裁剪后的图片
      const canvas = cropper.value.getCroppedCanvas({
        width: 200,
        height: 200,
        imageSmoothingQuality: 'high'
      })

      // 转换为Blob并上传
      canvas.toBlob(async (blob) => {
        if (blob) {
          const file = new File([blob], 'avatar.jpg', { type: 'image/jpeg' })
          const formData = new FormData()
          formData.append('file', file)

          const res = await uploadUserAvatarUsingPost({}, file)
          if (res.data.code === 0 && res.data.data) {
            // 上传成功
            form.value.userAvatar = res.data.data
            userLoginStore.setLoginUser({
              ...userLoginStore.loginUser,
              userAvatar: res.data.data,
            })
            message.success('头像更新成功')
            closeCropModal()
          } else {
            message.error('上传失败: ' + res.data.message)
          }
        }
      })
    } catch (error) {
      console.error('上传失败', error)
      message.error('上传失败，请重试')
    } finally {
      // 关闭加载状态
      Modal.destroyAll()
    }
  }
}

// 关闭裁剪模态框
const closeCropModal = () => {
  if (cropper.value) {
    cropper.value.destroy()
    cropper.value = null
  }
  cropVisible.value = false
  cropImageSrc.value = ''
  previewImage.value = ''
}

// 提交表单
const onFinish = async () => {
  try {
    const res = await updateUserInfoUsingPost({
      userAvatar: form.value.userAvatar,
      userName: form.value.userName,
      userProfile: form.value.userProfile,
    })

    if (res.data.code === 0) {
      message.success('保存成功，即将返回主页')
      userLoginStore.setLoginUser({
        ...userLoginStore.loginUser,
        userAvatar: form.value.userAvatar,
        userName: form.value.userName,
        userProfile: form.value.userProfile,
      })

      // 延迟1.5秒后返回主页
      setTimeout(() => {
        host()
      }, 1000)
    } else {
      message.error('保存失败: ' + res.data.message)
    }
  } catch (error) {
    console.error('保存失败', error)
    message.error('保存失败，请重试')
  }
}

// 处理提交（防止默认行为）
const handleSubmit = (e: Event) => {
  e.preventDefault()
  e.stopPropagation()
  formRef.value?.validate().then(() => {
    onFinish()
  })
}

// 返回首页
const host = () => {
  router.push('/')
}

// 初始化
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
#userInfoPage {
  transition: all 0.3s ease;
}

/* 头像样式 */
.avatar-col {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 0;
}

.avatar-container {
  position: relative;
  width: 160px;
  height: 160px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 4px solid white;
  transition: all 0.3s ease;
}

.avatar-container:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #8c8c8c;
}

.avatar-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.3s ease;
}

.avatar-btn {
  transform: translateY(10px);
  transition: transform 0.3s ease;
  background-color: rgba(255, 255, 255, 0.9);
  color: #1677ff;
  border: none;
}

.avatar-container:hover .avatar-btn {
  transform: translateY(0);
}

.avatar-hint {
  text-align: center;
  margin-top: 12px;
  color: #666;
}

/* 表单样式 */
:deep(.ant-form-item) {
  margin-bottom: 16px !important;
  transition: all 0.2s ease;
}

:deep(.ant-form-item:focus-within) {
  transform: translateX(4px);
}

:deep(.ant-form-item-label > label) {
  font-weight: 500 !important;
  color: #333 !important;
  font-size: 14px !important;
}

:deep(.ant-input),
:deep(.ant-input-textarea) {
  border-radius: 8px !important;
  border-color: #e5e7eb !important;
  transition: all 0.2s ease !important;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.02) !important;
}

:deep(.ant-input:focus),
:deep(.ant-input-textarea:focus) {
  border-color: #165dff !important;
  box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.1) !important;
  transform: translateY(-1px);
}

:deep(.ant-card) {
  border-radius: 12px !important;
  border: none !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06) !important;
  transition: all 0.3s ease !important;
}

:deep(.ant-card-head) {
  background-color: #fafafa !important;
  border-bottom: 1px solid #f0f0f0 !important;
  border-radius: 12px 12px 0 0 !important;
}

:deep(.ant-card-head-title) {
  color: #1f2937 !important;
  font-weight: 600 !important;
  font-size: 16px !important;
}

/* 裁剪模态框样式 */
.crop-container {
  padding: 10px 0;
}

.crop-box {
  width: 100%;
  height: 300px;
  overflow: hidden;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.crop-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.preview-container {
  margin-top: 20px;
}

.preview-boxes {
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

.preview-box {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-item {
  border-radius: 50%;
  background-size: cover;
  background-position: center;
  border: 1px solid #e5e7eb;
  transition: all 0.2s ease;
}

.preview-item:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-item.large {
  width: 80px;
  height: 80px;
}

.preview-item.medium {
  width: 60px;
  height: 60px;
}

.preview-item.small {
  width: 40px;
  height: 40px;
}

.preview-label {
  margin-bottom: 4px;
  color: #666;
}

/* 按钮样式 */
:deep(.ant-btn) {
  border-radius: 8px !important;
  transition: all 0.2s ease !important;
}

:deep(.ant-btn-primary) {
  border: none !important;
  height: 42px !important;
  position: relative;
  overflow: hidden;
}

/* 按钮悬停效果 */
:deep(.ant-btn-primary::before) {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(
    to right,
    rgba(255, 255, 255, 0) 0%,
    rgba(255, 255, 255, 0.3) 50%,
    rgba(255, 255, 255, 0) 100%
  );
  transform: rotate(30deg);
  transition: all 0.75s ease;
  opacity: 0;
}

:deep(.ant-btn-primary:hover::before) {
  opacity: 1;
  left: 125%;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .avatar-col {
    margin-bottom: 24px;
  }

  :deep(.ant-row) {
    flex-direction: column !important;
  }

  :deep(.ant-col) {
    width: 100% !important;
  }

  .crop-box {
    height: 250px;
  }
}
</style>
